import time


from channels.exceptions import StopConsumer


import json
import random
import requests

from chatgpt.chat import chat_with_openai

client_id = 'HQ24GgKkrXqxLbTPmlSkp1H6'
client_secret = '5RHkMKRCw9Qx159wZwYqLOnka6bnpeD7'


def unit_chat(chat_input, user_id=8888):
    chat_reply = '谢谢,客服不在，请稍等'
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s" % (
    client_id, client_secret)

    ret = requests.get(url)

    access_token = eval(ret.text)['access_token']

    post_data = {
        "log_id": str(random.random()),
        "request": {
            "query": chat_input,
            "user_id": user_id
        },
        "session_id": "",
        "service_id": "S103410",
        "version": "2.0"
    }
    # unit_chatbot_url = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + access_token
    unit_chatbot_url = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + access_token

    res = requests.post(unit_chatbot_url, json=post_data)
    unit_chat_obj = json.loads(res.content)
    # result-response_list-schema-intent_confidence-action_list-say
    if unit_chat_obj['error_code'] != 0:
        return chat_reply

    unit_chat_result = unit_chat_obj['result']
    unit_chat_response_list = unit_chat_result['response_list']
    unit_chat_response_obj = random.choice([unit_chat_response for unit_chat_response in unit_chat_response_list if
                                            unit_chat_response['schema']['intent_confidence'] > 0.0])
    unit_chat_action = unit_chat_response_obj['action_list']
    unit_chat_action_obj = random.choice(unit_chat_action)
    unit_chat_say = unit_chat_action_obj['say']

    return unit_chat_say

from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer

class YourConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        chat_input = "您要发送的聊天内容"
        chat_reply = unit_chat(chat_input)
        print(message)

        # 处理接收到的消息，可以在这里进行业务逻辑处理

        # 发送消息给前端
        await self.send(text_data=json.dumps({
            'message': chat_reply
        }))







